package com.ncmmall.mall.controller.business.goods;

import com.ncmmall.application.business.goods.GoodsBrandApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.brand.GoodsBrand;
import com.ncmmall.domain.business.goods.brand.QGoodsBrand;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * @Description: 商品品牌管理
 * @Date: 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/merchant/goods/brand")
public class GoodsBrandController {

    private final static Logger logger = LoggerFactory.getLogger(GoodsBrandController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsBrandApplication brandApplication;

    @Autowired
    private OperationLogApplication logApplication;

    @Value("${web.domain}")
    private String webDomain;

    /**
     * 品牌列表
     *
     * @param model
     * @param pageParams
     * @param goods
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, GoodsBrand brand) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());

        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());

        String hql = builderSQL("select u from GoodsBrand u where 1 = 1 and u.merchant.id = :id", params, brand);
        QueryPage<GoodsBrand> page = queryChannelService.findPage(hql, pageRequest.setParams(params), GoodsBrand.class);

        model.addAttribute("page", page).addAttribute("params", brand);

        return "merchant/goods/brand/list";
    }


    /**
     * 查看详情
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        GoodsBrand brand = queryChannelService.findOne(QGoodsBrand.goodsBrand.id.eq(id), GoodsBrand.class);

        model.addAttribute("brand", brand);

        return "merchant/goods/brand/detail";
    }


    /**
     * 编辑品牌信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        GoodsBrand brand = queryChannelService.findOne(QGoodsBrand.goodsBrand.id.eq(id), GoodsBrand.class);

        model.addAttribute("_method", "PUT").addAttribute("brand", brand);

        return "merchant/goods/brand/form";

    }

    /**
     * 编辑品牌信息
     *
     * @param requestWith
     * @param goods
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsBrand brand) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<GoodsBrand> items = queryChannelService.findAll(QGoodsBrand.goodsBrand.name.eq(brand.getName()).and(QGoodsBrand.goodsBrand.id.ne(brand.getId())), GoodsBrand.class);
            if (!items.isEmpty()) {
                return ImmutableMap.of("status", false, "message", "平台已存在该品牌");
            }


            brandApplication.modify(brand);
            logApplication.eventOfMerchant(Securitys.currentUser(), "修改品牌信息", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[编辑品牌信息异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 申请上架
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/applyPutaway", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> applyPutaway(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsBrand brand = queryChannelService.findOne(QGoodsBrand.goodsBrand.id.eq(id), GoodsBrand.class);

            brandApplication.applyPutaway(brand);
            logApplication.eventOfMerchant(Securitys.currentUser(), "提交品牌上架", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[编辑品牌信息异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 批量申请上架
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/applysPutaway", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> applysPutaway(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            brandApplication.applysPutaway(Lists.transform(ids, new Function<String, GoodsBrand>() {
                @Nullable
                @Override
                public GoodsBrand apply(@Nullable String input) {
                    GoodsBrand brand = queryChannelService.findOne(QGoodsBrand.goodsBrand.id.eq(Longs.tryParse(input)), GoodsBrand.class);
                    return brand;
                }
            }));

            logApplication.eventOfMerchant(Securitys.currentUser(), "批量提交品牌上架", Securitys.getIp(request));


            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量申请上架品牌异常]", e);
            return ImmutableMap.of("status", false);

        }
    }


    /**
     * 添加品牌页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {

        GoodsBrand brand = new GoodsBrand();
        model.addAttribute("_method", "POST").addAttribute("brand", brand);

        return "merchant/goods/brand/form";
    }

    /**
     * 添加品牌
     *
     * @param goods
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsBrand brand) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<GoodsBrand> items = queryChannelService.findAll(QGoodsBrand.goodsBrand.name.eq(brand.getName()), GoodsBrand.class);
            if (!items.isEmpty()) {
                return ImmutableMap.of("status", false, "message", "平台已存在该品牌");
            }


            brand.setMerchant(Securitys.currentUser());
            brandApplication.create(brand);
            logApplication.eventOfMerchant(Securitys.currentUser(), "添加品牌", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[添加品牌信息异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 删除品牌
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsBrand brand = queryChannelService.findOne(QGoodsBrand.goodsBrand.id.eq(id), GoodsBrand.class);

            brandApplication.remove(brand);
            logApplication.eventOfMerchant(Securitys.currentUser(), "删除品牌", Securitys.getIp(request));

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false);
        }

        return ImmutableMap.of("status", true);

    }

    /**
     * 条件筛选
     *
     * @param s
     * @param params
     * @param attribute
     * @return
     */
    private String builderSQL(String sql, Map<String, Object> params, GoodsBrand goods) {


        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status != 5 ";
        }

        return sql;
    }

}
